<?php

namespace App\Http\Controllers;

use App\Category;
use App\Http\Requests\ArticleRequest;
use Auth;

class UserArticleController extends Controller
{
    private $category;

    public function __construct(Category $category)
    {
        $this->category = $category;
    }

    public function index($userId)
    {
        $articles = Auth::user()->articles()->orderBy('created_at', 'DESC')->paginate(10);

        return view('article.index', compact('articles', 'userId'));
    }

    public function create($userId)
    {
        $header_title = '发表文章';
        $categories   = $this->category->pluck('name', 'id');

        return view('article.form', compact('header_title', 'userId', 'categories'));
    }

    public function store($userId, ArticleRequest $request)
    {
        Auth::user()->articles()->create($request->all());

        return redirect()->route('user.article.index', Auth::user());
    }

    public function edit($userId, $articleId)
    {
        $header_title = '编辑文章';
        $categories   = $this->category->pluck('name', 'id');
        $article      = Auth::user()->articles()->findOrFail($articleId);

        return view('article.form', compact('header_title', 'userId', 'categories', 'article'));
    }

    public function update($userId, $articleId, ArticleRequest $request)
    {
        Auth::user()->articles()->findOrFail($articleId)->update($request->all());

        return redirect()->route('user.article.index', Auth::user());
    }

    public function destroy($userId, $articleId)
    {
        Auth::user()->articles()->findOrFail($articleId)->delete();

        return redirect()->route('user.article.index', Auth::user());
    }
}
